module DisOrder
  class Pages
    extend Helpers

    def self.build(file, startFolder)
      return unless File.exist?(config("baseMetaDataFolder") + "/"+ file)

      template = ERB.new(baseTemplate(), 0, "%<>")

      @pages = YAML.load_file(config("baseMetaDataFolder") + "/"+ file)

      @pages.each_with_index do |f, i|
        puts "--- Make Page: #{f[1]["name"]}".white

        pageDir = "#{config("output")}/#{f[1]["url"] }"
        pageSource = "#{startFolder}/#{f[1]["folder"]}"
        cssSource = "#{pageSource}/css/"
        imageSource = "#{pageSource}/images/"
        jsSource = "#{pageSource}/js/"
        fontSource = "#{pageSource}/fonts/"

        FileUtils.mkdir_p(pageDir)
        puts "---- Created Folder: #{pageDir}".white

        file_name = sanitize_filename(f[1]["folder"])

        copySources(cssSource, outputCSS(), "css", file_name)
        copySources(imageSource, outputImages(), "images", file_name)
        copySources(jsSource, outputJS(), "js", file_name)
        copySources(fontSource, outputFonts(), "fonts", file_name)

        puts "---- Creating Page HTML".white
        if File.exist?(startFolder+ "/" +f[1]["folder"] +"/index.md")
          @ArticleText = render_markdown(File.new(startFolder+ "/" +f[1]["folder"] +"/index.md", encoding: "UTF-8").read)
          article = ERB.new(File.new(config("baseTemplateFolder") + "/" + config("articleHtml"), encoding: "UTF-8").read).result(binding)
          @contentBlock = ERB.new(article).result(binding)

          puts "----- Convertet  Markdown to HTML".white

        elsif  File.exist?(startFolder+ "/" +f[1]["folder"] +"/index.html")
          @contentBlock = ERB.new(File.new(startFolder+ "/" +f[1]["folder"] +"/index.html", encoding: "UTF-8").read).result(binding)

          puts "----- Got Page HTML ".white
        end

        if File.exist?(cssSource)
          @cssBlock = "static/css/#{file_name}/style.css"
        else
          @cssBlock = config("indexCSS")
        end
        @title = f[1]["name"]

        @jsBlock = nil
        if File.exist?(jsSource)
            jsfiles = Dir.entries(jsSource)
            jsfiles.delete "."
            jsfiles.delete ".."
            jsfiles.map! { |file| "/static/js/#{file_name}/#{file}" }
            @jsBlock = jsfiles
        end

        result = template.result(binding)

        File.open("#{pageDir}/index.html", mode: "w:UTF-8") do |f|
          f.write result
        end

        puts "---- Created HTML Page".white

        puts "--- Finished Page: #{f[1]["name"]} \n".white
      end
    end

    private
    def self.copySources(from, to, what, name)
      if File.exist?(from)
        FileUtils.mkdir_p(to)
        FileUtils.cp_r(from, to)
        FileUtils.mv("#{to}/#{what}", "#{to}/#{name}")
        puts "---- Copied #{what}".white
      end
    end
  end
end